package com.tongtech.iot.complaint.utils;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeanUtils;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

public class CustomerCopyUtils {

    /**
     * 复制源对象中不为空的属性到目标对象
     *
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyNonNullProperties(Object source, Object target) {
        if (source == null || target == null) {
            throw new IllegalArgumentException("Source and target must not be null");
        }

        // 获取源对象中不为空的属性名
        Set<String> nullPropertyNames = getNullPropertyNames(source);

        // 复制非空属性
        BeanUtils.copyProperties(source, target, nullPropertyNames.toArray(new String[0]));
    }

    /**
     * 获取对象中为空的属性名
     *
     * @param source 源对象
     * @return 为空的属性名集合
     */
    private static Set<String> getNullPropertyNames(Object source) {
        BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> nullPropertyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            String propertyName = pd.getName();
            Object propertyValue = src.getPropertyValue(propertyName);
            // 如果属性值为空，则添加到集合中
            if (propertyValue == null) {
                nullPropertyNames.add(propertyName);
            }
        }
        return nullPropertyNames;
    }
}